package org.black.phoneUtility.sms.reply.app.fragment;

import org.black.phoneUtility.PhoneUtilityConstant;
import org.black.phoneUtility.R;
import org.black.phoneUtility.sms.reply.app.activity.SmsReplyAddEditFragmentActivity;
import org.black.phoneUtility.sms.reply.app.service.SmsReplyScheduleNotifyNotificationInentService;
import org.black.phoneUtility.sms.reply.provider.SmsReplyContract;
import org.black.phoneUtility.sms.reply.widget.SmsReplyListCursorAdapter;
import org.black.phoneUtility.util.admob.AdmobConstant;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class SmsReplyListListFragment extends Fragment implements
		LoaderCallbacks<Cursor> {
	public static final String TAG = SmsReplyListListFragment.class.getName();
	private static final String LOG_TAG = SmsReplyListListFragment.class
			.getName();
	private ListView smsReplyList;
	private SmsReplyListCursorAdapter smsReplyListCursorAdapter;
	private AlertDialog.Builder forAskingDeleteSmsRepliesBuilder = null;
	private AlertDialog.Builder forAskingDeleteAllRecordsBuilder = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setHasOptionsMenu(true);
		forAskingDeleteSmsRepliesBuilder = new AlertDialog.Builder(
				getActivity());
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		this.smsReplyListCursorAdapter = new SmsReplyListCursorAdapter(
				getActivity(), null,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		this.smsReplyList.setAdapter(smsReplyListCursorAdapter);
		this.smsReplyList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Intent intent = new Intent(getActivity(),
								SmsReplyAddEditFragmentActivity.class);
						Bundle bundle = new Bundle();
						bundle.putLong(
								SmsReplyAddEditFragmentActivity.ARGUMENTS_SMS_REPLY_ID,
								id);
						intent.putExtras(bundle);
						startActivity(intent);
					}
				});
		this.smsReplyListCursorAdapter.notifyDataSetChanged();
		getActivity().getLoaderManager().initLoader(
				PhoneUtilityConstant.INIT_LOADER_SMS_REPLY_ID, null, this);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View result = inflater.inflate(R.layout.sms_reply_list, container,
				false);

		AdView adView = new AdView(getActivity());
		adView.setAdSize(AdSize.SMART_BANNER);
		adView.setAdUnitId(AdmobConstant.UNIT_ID);
		AdRequest adRequest = new AdRequest.Builder().build();
		LinearLayout adViewLayout = (LinearLayout) result
				.findViewById(R.id.adViewLayout);
		adViewLayout.addView(adView);
		adView.loadAd(adRequest);

		this.smsReplyList = (ListView) result
				.findViewById(R.id.smsReplyListView);
		TextView emptyTextView = (TextView) result
				.findViewById(R.id.smsReplyListViewNoDataTextView);
		emptyTextView
				.setText(getString(R.string.sms_reply_list_no_data_tap_vertical_and_horizontal_above_to_add_a_reply_setting_to_this_list));
		this.smsReplyList.setEmptyView(emptyTextView);
		this.smsReplyList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

		this.smsReplyList
				.setMultiChoiceModeListener(new MultiChoiceModeListener() {
					private int numberChoose = 0;

					@Override
					public boolean onPrepareActionMode(ActionMode mode,
							Menu menu) {
						MenuItem copyItem = menu
								.findItem(R.id.menu_sms_reply_list_choose_multi_items_copy);
						if (numberChoose > 1) {
							copyItem.setVisible(false);
						} else {
							copyItem.setVisible(true);
						}
						return true;
					}

					@Override
					public void onDestroyActionMode(ActionMode mode) {
						smsReplyListCursorAdapter.clearSelection();

					}

					@Override
					public boolean onCreateActionMode(ActionMode mode, Menu menu) {
						numberChoose = 0;
						MenuInflater inflater = getActivity().getMenuInflater();
						inflater.inflate(
								R.menu.sms_reply_list_choose_multi_items, menu);
						return true;
					}

					@Override
					public boolean onActionItemClicked(final ActionMode mode,
							MenuItem item) {
						switch (item.getItemId()) {
						case R.id.menu_sms_reply_list_choose_multi_items_delete:
							forAskingDeleteSmsRepliesBuilder
									.setMessage(getString(
											R.string.sms_reply_list_dialog_message_do_you_really_want_to_delete_numbers_settings,
											String.valueOf(numberChoose)));
							forAskingDeleteSmsRepliesBuilder.setPositiveButton(
									android.R.string.ok,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											numberChoose = 0;
											smsReplyListCursorAdapter
													.removeSelections();
											mode.finish();

											Intent scheduleNotifyNotificationServiceIntent = new Intent(
													getActivity(),
													SmsReplyScheduleNotifyNotificationInentService.class);
											Bundle argumentsForSchedule = new Bundle();
											argumentsForSchedule
													.putInt(SmsReplyScheduleNotifyNotificationInentService.ARGUMENTS_ACTION_TYPE,
															SmsReplyScheduleNotifyNotificationInentService.ACTION_TYPE_RECHECK);
											scheduleNotifyNotificationServiceIntent
													.putExtras(argumentsForSchedule);
											getActivity()
													.startService(
															scheduleNotifyNotificationServiceIntent);
											Log.d(LOG_TAG,
													"Start SmsReplyScheduleNotifyNotificationInentService!");
										}
									}).setNegativeButton(
									android.R.string.cancel,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
										}
									});

							forAskingDeleteSmsRepliesBuilder.show();
							return true;
						case R.id.menu_sms_reply_list_choose_multi_items_copy:
							smsReplyListCursorAdapter.copy();
							numberChoose = 0;
							mode.finish();
							return true;
						}
						return false;
					}

					@Override
					public void onItemCheckedStateChanged(ActionMode mode,
							int position, long id, boolean checked) {
						if (checked) {
							numberChoose++;
							smsReplyListCursorAdapter.addSelection(position,
									checked);
						} else {
							numberChoose--;
							smsReplyListCursorAdapter.removeSelection(position);
						}
						mode.setTitle(String.valueOf(numberChoose));
						mode.invalidate();

					}
				});
		this.forAskingDeleteAllRecordsBuilder = new AlertDialog.Builder(
				getActivity());
		this.forAskingDeleteAllRecordsBuilder
				.setMessage(R.string.sms_schedule_list_do_you_really_want_to_clear_all_settings);
		this.forAskingDeleteAllRecordsBuilder.setPositiveButton(
				android.R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						getActivity().getContentResolver().delete(
								SmsReplyContract.SmsReplies.CONTENT_URI, null,
								null);
						Log.i(LOG_TAG, "Delete all sms schedule records");
						Intent scheduleNotifyNotificationServiceIntent = new Intent(
								getActivity(),
								SmsReplyScheduleNotifyNotificationInentService.class);
						Bundle argumentsForSchedule = new Bundle();
						argumentsForSchedule
								.putInt(SmsReplyScheduleNotifyNotificationInentService.ARGUMENTS_ACTION_TYPE,
										SmsReplyScheduleNotifyNotificationInentService.ACTION_TYPE_RECHECK);
						scheduleNotifyNotificationServiceIntent
								.putExtras(argumentsForSchedule);
						getActivity().startService(
								scheduleNotifyNotificationServiceIntent);
						Log.d(LOG_TAG,
								"Start SmsReplyScheduleNotifyNotificationInentService!");
					}
				}).setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}

				});

		return result;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.sms_reply_list_actions, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getActivity().onBackPressed();
			return false;
		case R.id.menu_sms_reply_list_add:
			Intent intent = new Intent(getActivity(),
					SmsReplyAddEditFragmentActivity.class);
			Bundle bundle = new Bundle();

			intent.putExtras(bundle);
			startActivity(intent);
			return true;
		case R.id.menu_sms_reply_list_clear_all:
			this.forAskingDeleteAllRecordsBuilder.show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		return new CursorLoader(getActivity(),
				SmsReplyContract.SmsReplies.CONTENT_URI, null, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		if (data != null && data.moveToFirst() == true) {
			if (smsReplyListCursorAdapter != null) {
				smsReplyListCursorAdapter.swapCursor(data);
				smsReplyListCursorAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		smsReplyListCursorAdapter.swapCursor(null);
	}
}
